import { toLogin, getDeptDetail } from "@/apis/login";
import { Message, Modal } from "view-design";
import router from "@/router/index";
import { tenantId } from "@/utils/setting.js";
const state = {
    userInfo: JSON.parse(sessionStorage.getItem("info")),
    token: localStorage.getItem("token"),
    tenantId: tenantId,
    deptLevelNum: 0,
};
// 存放的方法
const mutations = {
    // 设置userInfo
    setUserInfo(state, data) {
        state.userInfo = data;
    },
    // 清除用户信息
    setClearUserInfo(state) {
        // 清除用户信息、token
        localStorage.removeItem("token");
        sessionStorage.removeItem("info");
        state.userInfo = null;
        state.deptLevelNum = 0;
    },
    // 设置token
    setToken(state, data) {
        state.token = data;
    },
    // 循环次数
    setNum(state) {
        state.deptLevelNum += 1;
    },
    // 重置循环次数
    noneNum(state) {
        state.deptLevelNum = 0;
        sessionStorage.removeItem("info");
    },
};
const actions = {
    // 部门
    async getDeptDetail({ commit, dispatch }, userInfo) {
        let result = null;
        try {
            let params = {
                deptCode: userInfo.deptCode,
            };
            result = await getDeptDetail(params);
            if (result.code == 0) {
                // userInfo.deptLevel = null;
                userInfo.deptLevel = result.data.deptLevel;
                userInfo.parentCode = result.data.parentCode;
                userInfo.codePaths = result.data.codePaths;
                if (result.data.deptType != null && result.data.deptType == 2) {
                    userInfo.deptCode =
                        result.data.parentCode === "0001A110000000000IOJ"
                            ? "0001A110000000000IMR"
                            : result.data.parentCode;
                    userInfo.departmentId =
                        result.data.parentCode === "0001A110000000000IOJ"
                            ? "0001A110000000000IMR"
                            : result.data.parentCode;
                    userInfo.deptName = result.data.name;
                    userInfo.username = result.data.parentName;
                }
                if (result.data.deptType != null && result.data.deptType == 3) {
                    userInfo.deptLevel = 1;
                    userInfo.deptCode = "0001A110000000000IMR";
                    userInfo.departmentId = "0001A110000000000IMR";
                    userInfo.deptName = "国家管网集团";
                    userInfo.username = result.data.parentName;
                }
                commit("setUserInfo", userInfo);
                sessionStorage.setItem("info", JSON.stringify(userInfo));
                // 级别为空，调三次，看是否进入页面
                if (
                    userInfo.deptLevel == null ||
                    userInfo.deptLevel == "null"
                ) {
                    //
                    if (state.deptLevelNum == "3") {
                        Modal.confirm({
                            title: "警告",
                            content:
                                "<p>部门级别获取失败，会影响各别权限无法操作，是否进入页面",
                            okText: "确定",
                            cancelText: `重新加载`,
                            width: 500,
                            onOk: () => {
                                // document.write("进入");
                                // 跳转页面
                                setTimeout(() => {
                                    // router.push('/siteInspectionHome').catch(_error => { })
                                    let path = window.location.href
                                        .split("/#")[1]
                                        .split("?token=")[0];
                                    router.push(path).catch((_error) => {});
                                    location.reload();
                                }, 0);
                            },
                            onCancel: () => {
                                // document.write("不进");
                                // return false;
                                commit("noneNum");
                                dispatch("getDeptDetail", state.userInfo);
                            },
                        });
                    } else {
                        commit("setNum");
                        dispatch("getDeptDetail", state.userInfo);
                    }
                } else {
                    // 跳转页面
                    setTimeout(() => {
                        // router.push('/siteInspectionHome').catch(_error => { })
                        let path = window.location.href
                            .split("/#")[1]
                            .split("?token=")[0];
                        router.push(path).catch((_error) => {});
                        location.reload();
                    }, 0);
                }
            }
        } catch (error) {}
    },
    /**
     * @description: 登录
     * @param {*} commit 调用mutations
     * @param {*} data 用户信息
     * @return {*} 接口返回信息
     */
    async login({ commit }, data) {
        let result = null;
        try {
            result = await toLogin(data);
            if (result.code == 0) {
                const userInfo = {
                    departmentId: result.data.sysUser.deptCode,
                    // "departmentId": "0001A11000000000S6HI",
                    deptId: result.data.sysUser.deptId,
                    userId: result.data.sysUser.userId,
                    username: result.data.sysUser.alias,
                    deptName: result.data.sysUser.deptName,
                    email: result.data.sysUser.email,
                    phone: result.data.sysUser.phone,
                    name: result.data.sysUser.alias,
                    deptLevel: result.data.sysUser.deptLevel,
                    deptCode: result.data.sysUser.deptCode,
                    // "deptCode": "0001A11000000000S6HI",
                    role: "all",
                };
                commit("setUserInfo", userInfo);
                sessionStorage.setItem("info", JSON.stringify(userInfo));
            }
        } catch (error) {
            if (error.code === 10001) {
                Message.error("用户名或密码错误,请重新输入！");
            } else {
                Message.error("登录失败，请重新登录！");
            }
        } finally {
            return result;
        }
    },
    /**
     * @description: 退出
     * @param {*} commit 调用mutations
     * @return {*} null
     */
    logout({ commit }) {
        // 清除vuex中用户信息
        commit("setClearUserInfo");
        // 清除session
        sessionStorage.clear();
        // 回撤
        router.go(0);
        // router.push('/login').catch(error => { })
    },
};

export default {
    namespaced: true,
    state,
    mutations,
    actions,
};
